<template>
  <view class="login-container">
    <!-- 顶部Logo区域 -->
    <view class="logo-section">
      <image class="logo" src="/static/images/logo.png" mode="aspectFit"></image>
      <text class="app-name">智慧社区</text>
      <text class="app-slogan">让生活更美好</text>
    </view>

    <!-- 登录表单 -->
    <view class="login-form">
      <u-form :model="loginForm" :rules="loginRules" ref="loginForm">
        <!-- 用户名输入框 -->
        <u-form-item prop="username">
          <u-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefixIcon="account"
            clearable
            :border="false"
            class="input-item"
          />
        </u-form-item>

        <!-- 密码输入框 -->
        <u-form-item prop="password">
          <u-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefixIcon="lock"
            clearable
            :border="false"
            class="input-item"
          />
        </u-form-item>

        <!-- 验证码输入框 -->
        <u-form-item prop="captcha">
          <view class="captcha-container">
            <u-input
              v-model="loginForm.captcha"
              placeholder="请输入验证码"
              prefixIcon="checkmark-circle"
              clearable
              :border="false"
              class="captcha-input"
            />
            <image 
              :src="captchaUrl" 
              @click="refreshCaptcha" 
              class="captcha-image"
              mode="aspectFit"
            />
          </view>
        </u-form-item>

        <!-- 记住密码选项 -->
        <view class="remember-section">
          <u-checkbox v-model="rememberPassword" shape="circle">
            <text class="remember-text">记住密码</text>
          </u-checkbox>
          <text class="forgot-password" @click="forgotPassword">忘记密码？</text>
        </view>

        <!-- 登录按钮 -->
        <u-button
          type="primary"
          :loading="loading"
          :disabled="loading"
          @click="handleLogin"
          class="login-button"
        >
          {{ loading ? '登录中...' : '登录' }}
        </u-button>

        <!-- 注册链接 -->
        <view class="register-section">
          <text class="register-text">还没有账号？</text>
          <text class="register-link" @click="goToRegister">立即注册</text>
        </view>
      </u-form>
    </view>

    <!-- 底部版权信息 -->
    <view class="footer">
      <text class="copyright">© 2025 智慧社区管理系统</text>
    </view>
  </view>
</template>

<script>
/**
 * 移动端登录页面
 * @author Wu.Liang
 */
export default {
  name: 'Login',
  data() {
    return {
      // 登录表单数据
      loginForm: {
        username: '',
        password: '',
        captcha: '',
        captchaKey: ''
      },
      // 表单验证规则
      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '用户名长度在3-20个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度在6-20个字符之间', trigger: 'blur' }
        ],
        captcha: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { len: 4, message: '验证码长度为4位', trigger: 'blur' }
        ]
      },
      // 记住密码
      rememberPassword: false,
      // 验证码图片URL
      captchaUrl: '',
      // 加载状态
      loading: false
    }
  },

  onLoad() {
    // 页面加载时检查自动登录
    this.checkAutoLogin()
    // 生成验证码
    this.refreshCaptcha()
  },

  onShow() {
    // 页面显示时检查登录状态
    this.checkLoginStatus()
  },

  methods: {
    /**
     * 检查自动登录
     */
    checkAutoLogin() {
      const token = uni.getStorageSync('token')
      const rememberPassword = uni.getStorageSync('rememberPassword')
      
      if (token && rememberPassword) {
        // 验证Token有效性
        this.validateToken(token)
      } else if (rememberPassword) {
        // 恢复记住的用户名密码
        const savedUsername = uni.getStorageSync('savedUsername')
        const savedPassword = uni.getStorageSync('savedPassword')
        if (savedUsername && savedPassword) {
          this.loginForm.username = savedUsername
          this.loginForm.password = savedPassword
          this.rememberPassword = true
        }
      }
    },

    /**
     * 验证Token有效性
     */
    async validateToken(token) {
      try {
        const result = await this.$api.auth.checkLoginStatus()
        if (result.data) {
          // Token有效，直接跳转到首页
          this.goToHome()
        }
      } catch (error) {
        // Token无效，清除存储的登录信息
        uni.removeStorageSync('token')
        uni.removeStorageSync('userInfo')
        uni.removeStorageSync('userMenus')
      }
    },

    /**
     * 检查登录状态
     */
    checkLoginStatus() {
      const token = uni.getStorageSync('token')
      if (token) {
        // 已登录，跳转到首页
        this.goToHome()
      }
    },

    /**
     * 刷新验证码
     */
    async refreshCaptcha() {
      try {
        const result = await this.$api.auth.generateImageCaptcha()
        this.captchaUrl = result.data.imageUrl
        this.loginForm.captchaKey = result.data.captchaKey
      } catch (error) {
        uni.showToast({
          title: '获取验证码失败',
          icon: 'error'
        })
      }
    },

    /**
     * 处理登录
     */
    async handleLogin() {
      // 表单验证
      const valid = await this.$refs.loginForm.validate()
      if (!valid) {
        return
      }

      this.loading = true

      try {
        console.log('开始登录，登录数据:', this.loginForm)
        
        // 1. 登录接口
        const result = await this.$api.auth.login(this.loginForm)
        console.log('登录响应:', result)
        
        if (result.code === 200) {
          const data = result.data
          
          // 2. 保存Token
          uni.setStorageSync('token', data.token)
          uni.setStorageSync('refreshToken', data.refreshToken || '')
          uni.setStorageSync('tokenExpireTime', Date.now() + (data.expireIn || 7200) * 1000)

          // 3. 构建用户信息（直接使用登录接口返回的数据）
          const userInfo = {
            id: data.userId || data.user?.id,
            username: data.username || data.user?.username,
            nickname: data.nickname || data.user?.nickname || data.realName || data.user?.realName,
            realName: data.realName || data.user?.realName,
            phone: data.phone || data.user?.phone,
            email: data.email || data.user?.email,
            avatar: data.avatar || data.user?.avatar,
            userType: data.userType || data.user?.userType,
            userTypeName: data.userTypeName || data.user?.userTypeName,
            status: data.status || data.user?.status || 1,
            createTime: data.createTime || data.user?.createTime || new Date().toISOString(),
            updateTime: data.updateTime || data.user?.updateTime || new Date().toISOString(),
            lastLoginTime: data.lastLoginTime || data.user?.lastLoginTime,
            lastLoginIp: data.lastLoginIp || data.user?.lastLoginIp,
            roles: data.roles || data.user?.roles || [],
            permissions: data.permissions || data.menuPermissions || [],
            propertyCompanyId: data.propertyCompanyId || data.user?.propertyCompanyId
          }
          
          // 4. 保存用户信息
          uni.setStorageSync('userInfo', userInfo)
          uni.setStorageSync('userPermissions', JSON.stringify(data.permissions || data.menuPermissions || []))
          uni.setStorageSync('userMenus', data.menus || [])
          
          // 5. 同步到userStore
          try {
            const { useUserStore } = require('@/store/user')
            const userStore = useUserStore()
            userStore.syncUserInfo(userInfo)
            console.log('登录后用户信息已同步到userStore:', userInfo)
          } catch (error) {
            console.warn('登录后同步用户信息到userStore失败:', error)
          }
          
          // 6. 处理记住密码
          this.handleRememberPassword()
          
          // 7. 延长loading时间，确保信息设置完毕
          await new Promise(resolve => setTimeout(resolve, 1500))
          
          // 8. 关闭loading，跳转首页
          this.loading = false
          uni.showToast({ title: '登录成功', icon: 'success' })
          setTimeout(() => this.goToHome(), 1000)
        } else {
          throw new Error(result.message || '登录失败')
        }
      } catch (error) {
        this.loading = false
        uni.showToast({ title: error.message || '登录失败，请稍后重试', icon: 'error' })
      }
    },

    /**
     * 保存登录信息
     */
    saveLoginInfo(data) {
      // 保存Token
      uni.setStorageSync('token', data.token)
      uni.setStorageSync('refreshToken', data.refreshToken || '')
      uni.setStorageSync('tokenExpireTime', Date.now() + (data.expireIn || 7200) * 1000)
      
      // 构建用户信息对象（与登录接口返回结构保持一致）
      const userInfo = {
        id: data.userId || data.user?.id,
        username: data.username || data.user?.username,
        nickname: data.nickname || data.user?.nickname || data.realName || data.user?.realName,
        realName: data.realName || data.user?.realName,
        phone: data.phone || data.user?.phone,
        email: data.email || data.user?.email,
        avatar: data.avatar || data.user?.avatar,
        userType: data.userType || data.user?.userType,
        userTypeName: data.userTypeName || data.user?.userTypeName,
        status: data.status || data.user?.status || 1,
        createTime: data.createTime || data.user?.createTime || new Date().toISOString(),
        updateTime: data.updateTime || data.user?.updateTime || new Date().toISOString(),
        lastLoginTime: data.lastLoginTime || data.user?.lastLoginTime,
        lastLoginIp: data.lastLoginIp || data.user?.lastLoginIp,
        roles: data.roles || data.user?.roles || [],
        permissions: data.permissions || data.menuPermissions || [],
        propertyCompanyId: data.propertyCompanyId || data.user?.propertyCompanyId
      }
      
      // 保存用户信息
      uni.setStorageSync('userInfo', userInfo)
      
      // 保存菜单权限
      uni.setStorageSync('userMenus', data.menuPermissions || data.permissions || [])
      uni.setStorageSync('userPermissions', JSON.stringify(data.permissions || data.menuPermissions || []))
      
      // 保存登录时间
      uni.setStorageSync('loginTime', new Date().getTime())
      
      // 同步用户信息到userStore
      try {
        const { useUserStore } = require('@/store/user')
        const userStore = useUserStore()
        userStore.syncUserInfo(userInfo)
        console.log('登录后用户信息已同步到userStore:', userInfo)
      } catch (error) {
        console.warn('登录后同步用户信息到userStore失败:', error)
      }
    },

    /**
     * 处理记住密码
     */
    handleRememberPassword() {
      if (this.rememberPassword) {
        // 保存用户名和密码
        uni.setStorageSync('savedUsername', this.loginForm.username)
        uni.setStorageSync('savedPassword', this.loginForm.password)
        uni.setStorageSync('rememberPassword', true)
      } else {
        // 清除保存的用户名和密码
        uni.removeStorageSync('savedUsername')
        uni.removeStorageSync('savedPassword')
        uni.removeStorageSync('rememberPassword')
      }
    },

    /**
     * 跳转到首页
     */
    goToHome() {
      uni.switchTab({
        url: '/pages/index/index'
      })
    },

    /**
     * 跳转到注册页面
     */
    goToRegister() {
      uni.navigateTo({
        url: '/pages/register/index'
      })
    },

    /**
     * 忘记密码
     */
    forgotPassword() {
      uni.navigateTo({
        url: '/pages/forgot-password/index'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  padding: 0 40rpx;
}

.logo-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-top: 100rpx;

  .logo {
    width: 120rpx;
    height: 120rpx;
    margin-bottom: 30rpx;
  }

  .app-name {
    font-size: 48rpx;
    font-weight: bold;
    color: #ffffff;
    margin-bottom: 10rpx;
  }

  .app-slogan {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.8);
  }
}

.login-form {
  background: #ffffff;
  border-radius: 20rpx;
  padding: 60rpx 40rpx;
  margin-bottom: 60rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);

  .input-item {
    margin-bottom: 30rpx;
    background: #f8f9fa;
    border-radius: 10rpx;
    padding: 20rpx;
  }

  .captcha-container {
    display: flex;
    align-items: center;
    gap: 20rpx;

    .captcha-input {
      flex: 1;
      background: #f8f9fa;
      border-radius: 10rpx;
      padding: 20rpx;
    }

    .captcha-image {
      width: 120rpx;
      height: 80rpx;
      border-radius: 8rpx;
      border: 1rpx solid #e0e0e0;
    }
  }

  .remember-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 30rpx 0;

    .remember-text {
      font-size: 28rpx;
      color: #666666;
    }

    .forgot-password {
      font-size: 28rpx;
      color: #667eea;
    }
  }

  .login-button {
    width: 100%;
    height: 88rpx;
    border-radius: 44rpx;
    font-size: 32rpx;
    font-weight: bold;
    margin: 40rpx 0;
  }

  .register-section {
    text-align: center;
    margin-top: 30rpx;

    .register-text {
      font-size: 28rpx;
      color: #666666;
    }

    .register-link {
      font-size: 28rpx;
      color: #667eea;
      margin-left: 10rpx;
    }
  }
}

.footer {
  text-align: center;
  padding-bottom: 40rpx;

  .copyright {
    font-size: 24rpx;
    color: rgba(255, 255, 255, 0.6);
  }
}
</style> 